import { serviceStart, serviceStop } from "@/api/modules/service/service";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { ProductStatusEnum } from "@/enums/statusEnum";
import { useApplet } from "@/hooks/useApplet";
import { useAuthButtonList } from "@/hooks/useAuthButtons";
import { filePrefix } from "@/hooks/useSystem";
import { dataFormat } from "@/utils/format";
import { matchIp } from "@/utils/str";
import { confirm, showMsg, showTips } from "@/utils/util";
import AppletLogo from "@public/images/applet/applet.png";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { addUserApplet, delUserApplet, getUserAppletList, modUserApplet } from "../../../api/modules/applet/userApplet";
import "../applet.scss";
import BasicDialog from "../components/detailDialog";
import { Applet } from "./../../../api/interface/iot";
export default defineComponent({
	name: "ProductList",
	setup() {
		const router = useRouter();
		const buttonsList = ref<any>([]);
		const operateList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			let btns = await useAuthButtonList();
			buttonsList.value = btns.filter((item: any) => item.type == "btn");
			operateList.value = btns.filter((item: any) => (item.type = "operate"));
		});
		const initParam = reactive<Applet.ReqUserApplet>({
			pageSize: buttonsList.value.filter((item: any) => item.path == "add") ? 11 : 12
		});
		const { gotoAccess } = useApplet();

		const dataCallback = (data: any) => {
			data.records.map((item: any) => {
				item.status = item.status + "";
				return item;
			});
			data.records.unshift({});
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current || 1,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return getUserAppletList(params);
		};
		const detailDialog = reactive<any>({
			title: "添加应用",
			detail: {},
			visible: false
		});
		const clickBtn = async (fn: string, row: any) => {
			let selected: any[] = row.selectList ? row.selectList : row.id ? [row] : [row.row];
			switch (fn) {
				case "mod":
					if (selected.length != 1) {
						showMsg("请选择一条记录", MessageType.warning);
						return;
					}
					detailDialog.detail = selected[0];
					detailDialog.title = "修改应用";
					detailDialog.visible = true;
					break;
				case "detail":
					if (selected.length != 1) {
						showMsg("请选择一条记录", MessageType.warning);
						return;
					}
					router.push({ path: RouterPath.appletDetail1, query: { id: selected[0].id, key: selected[0].key } });
					break;
				case "add":
					detailDialog.detail = {};
					detailDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg("请选择要删除的数据", MessageType.warning);
						return;
					}
					confirm({ content: "删除后无法找回，确定删除当前选择的应用" }).then(flag => {
						flag && submitDel({ id: selected.map(item => item.id).join(",") });
					});
					break;
				case "copy":
					if (selected.length != 1) {
						showMsg("请选择一条要复制的应用记录", MessageType.warning);
						return;
					}
					copyProductDialog.visible = true;
					copyProductDialog.formData = JSON.parse(JSON.stringify(selected[0]));
					copyProductDialog.formData.id = selected[0].model;
					break;
				case "start":
					if (selected.length != 1) {
						showMsg("请选择一条记录", MessageType.warning);
						return;
					}
					startService(selected);
					break;
				case "stop":
					if (selected.length != 1) {
						showMsg("请选择一条记录", MessageType.warning);
						return;
					}
					stopService(selected);
					break;
			}
		};

		const startService = async (selected: any) => {
			let { code, message } = await serviceStart({ id: selected[0].svcId });
			showTips(code, "启动应用", message);
		};
		const stopService = async (selected: any) => {
			let { code, message } = await serviceStop({ id: selected[0].svcId });
			showTips(code, "停止应用", message);
		};
		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			// { prop: "model", label: "应用编码", search: { el: "input" } },
			{ prop: "name", label: "应用名称", search: { el: "input" } },
			// { prop: "status", label: "应用状态", search: { slot: {} } },
			// { prop: "deviceType", label: "应用类型", search: { slot: {} } },
			// { prop: "deptName", label: "所属分组", search: { slot: {} } },
			{ prop: "descript", label: "应用描述" },
			{ prop: "createTime", label: "创建时间" },
			{ prop: "operation", label: "操作", fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const submitDel = async (dataInfo: any) => {
			let res = await delUserApplet({ ...dataInfo });
			let ok = showTips(res.code, "删除应用", res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submitAdd = async () => {
			let api = detailDialog.detail.id ? modUserApplet : addUserApplet;
			let res = await api({ ...detailDialog.detail });
			let ok = showTips(res.code, "添加应用", res.message);
			if (ok) {
				detailDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		const copyProductDialog = reactive<any>({
			visible: false,
			formData: {}
		});
		return () => {
			return (
				<div class="applet-page">
					{/* <div style="width:100px">
						<TypedJs prefix={`组态信息 `} dataList={[`打字机打字机打字机打字机打字机打字机打字机打字机打字机打字机打字机`]} />
					</div> */}
					<BasicDialog
						width="800px"
						title={detailDialog.title}
						v-model:visible={detailDialog.visible}
						detail={detailDialog.detail}
						onSubmit={submitAdd}
					></BasicDialog>
					<ProTable
						ref={proTable}
						showHeader={false}
						title={buttonsList.value.length ? "" : "应用管理"}
						columns={columns}
						noList
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
						searchCol={5}
						toolbar={["grid"]}
						viewType="grid"
						gridSpan={6}
						hideCardCheck
					>
						{{
							tableHeader: (scope: any) => {
								return buttonsList.value
									.filter((item: any) => item.path != "add")
									.map((item: any) => {
										return (
											<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
												<i class={`iconfont ${item.icon}`}></i>
												{item.menuName}
											</el-button>
										);
									});
							},
							cardBody: (scope: any) => {
								return (
									<div class="applet-card shadow-md">
										<div class="bg"></div>
										<div class="applet-container">
											{scope.row.id ? (
												<div class="flex p-8">
													<div class="applet-img pr-4">
														<el-image
															lazy
															style="width:120px;height:120px;"
															src={scope.row.logo ? `${filePrefix()}${scope.row.logo}` : AppletLogo}
															fit="fill"
														></el-image>
														<div class="flex justify-center mt-4">
															{operateList.value.some((item: any) => item.component == "del") && (
																<el-button size="small" onClick={() => clickBtn("del", scope.row)}>
																	删除
																</el-button>
															)}
															{operateList.value.some((item: any) => item.component == "detail") && (
																<el-button size="small" onClick={() => clickBtn("detail", scope.row)}>
																	详情
																</el-button>
															)}
														</div>
													</div>
													<div class="flex-1">
														<div class="text-lg ">
															<span class="font-bold">{scope.row.name}</span>
															<span class="text-sm p-4">{scope.row.key}</span>
														</div>
														<div class="desc pt-4 text-gray-500 h-28 leading-7">{scope.row.desc}</div>
														<div class="pt-8">
															<el-button
																type="primary"
																onClick={() => {
																	if (matchIp(window.location.host)) {
																		ElMessage.warning("使用域名访问平台时生成");
																	} else {
																		gotoAccess(scope.row);
																	}
																}}
															>
																打开应用
																<i class="iconfont iconarrow-right ml-2" style="font-size:14px" />
															</el-button>
														</div>
													</div>
												</div>
											) : (
												<div
													onClick={() => clickBtn("add", scope)}
													class="cursor-pointer"
													style="margin: auto;position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);text-align: center;"
												>
													<div>
														<i class="iconfont iconplus-circle" style="font-size:25px"></i>
													</div>
													<div class="text-base">添加</div>
												</div>
											)}
										</div>
									</div>
								);
							},
							status: (scope: any) => {
								return (
									<OnlineStatus
										v-model={scope.row.status}
										onlineLabel={ProductStatusEnum.DEPLOY_LABEL}
										offlineLabel={ProductStatusEnum.DEVELOP_LABEL}
									/>
								);
							},
							model: (scope: any) => {
								return (
									<el-link type="primary" onClick={() => clickBtn("details", scope.row)}>
										{scope.row.model}
									</el-link>
								);
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							operation: (scope: any) => {
								return (
									<>
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("details", scope.row);
											}}
										>
											详情
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<Empty
										class="text-left leading-6"
										subtitle="应用服务，面向物联网应用开发者，提供基于三三物联的一键式应用容器化托管、部署及运维能力，实现物联网应用的快速接入及应用的低成本复制。物联网应用托管涉及镜像管理、应用配置、应用部署操作。"
										title="暂无应用"
										btnText="立即添加应用"
										onAdd={(scope: any) => {
											clickBtn("add", scope);
										}}
									/>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
